<?php
// Library File
include 'lib/library.php';

// URL address
$addr = address();

// Local address
$rel_addr = relative_address();

// Database Connection
include $rel_addr.'/lib/mysql_connect.inc';

// Header File
include $rel_addr.'/lib/header.php';

// Footer File
include $rel_addr.'/lib/footer.php';

$title = 'Message Center';
$subtitle = 'Message Center';

// if logged in
if(isset($m_user_id)){
	$content .= '
		<div class="inbox">
			<div class="linksbox">
	';
			
			// The pages GET variable
			// changes what is displayed
			$mode = $_GET['mode'];
			
			// Make box active if neccessary
			if(!isset($mode)){
				$content .= '<div class="box active" '.click_refresh().'><P>Inbox</P></div>';
			}else{
				$content .= '<div class="box" '.click_refresh().'><P>Inbox</P></div>';
			}
			
			// Make box active if neccessary
			if($mode == 'sent'){
				$content .= '<div class="box active" '.click_get('mode', 'sent').'><P>Sent</P></div>';
			}else{
				$content .= '<div class="box" '.click_get('mode', 'sent').'><P>Sent</P></div>';
			}
			
				// Spacer to push compose button to the right
				$content .= '<div class="spacer"><P></P></div>';
			
			// Make box active if neccessary
			if($mode == 'compose'){
				$content .= '<div class="box compose active" '.click_get('mode', 'compose').'><P>Compose Message</P></div>';
			}else{
				$content .= '<div class="box compose" '.click_get('mode', 'compose').'><P>Compose Message</P></div>';
			}
	
	// Close linksbox div
	$content .= '
			</div>
	';
	
	// Display the toolbar
	// for every mode except compose
	if($mode != 'compose' && !isset($_GET['read'])){
		$content .= '
			<script language="javascript" type="text/javascript">
				function selector(mode){
					
					alert(mode.innerhtml);
					if(mode == "All"){
						
					}else if(mode == "Unread"){
					
					}else if(mode == "Read"){
						
					}else if(mode == "None"){
						alert("DUDE");
						uncheckall(document.getElementsByName("check"));
					}
				}
				function checkall(check){
					for (i = 0; i < check.length; i++)
						check[i].checked = true ;
					}
				}
				function uncheckall(check){
					for (i = 0; i < check.length; i++)
						check[i].checked = false ;
					}
				}
			</script>
		';
		$content .= '
			<div class="toolbar">
			<label id="test" for="selectmenu">Select:</label><select id="selectmenu" name="selectmenu" onchange="selector(this.value)">
					<option value="">---</option>
					<option value="None">None</option>
					<option value="Read">Read</option>
					<option value="Unread">Unread</option>
					<option value="All">All</option>
				</select>
			<UL>
			<li><P>Mark as Unread</P></li>
			<li><P>Mark as Read</P></li>
			<li><P>Delete</P></li>
			</UL>
			
			</div>
		';
	
	}

	// Set to normal inbox mode
	// retrieve and display messages
	if(!isset($mode) && !isset($_GET['read'])){
		
		$content .= '
			<script language="javascript" type="text/javascript">
			
			function update_message( message_id ){
				var ajaxRequest;  // The variable that makes Ajax possible!
				
				try{
					// Opera 8.0+, Firefox, Safari
					ajaxRequest = new XMLHttpRequest();
				} catch (e){
					// Internet Explorer Browsers
					try{
						ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
					} catch (e) {
						try{
							ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
						} catch (e){
							// Something went wrong
							alert("Your browser broke!");
							return false;
						}
					}
				}
				// Create a function that will receive data sent from the server
				ajaxRequest.onreadystatechange = function(){
					if(ajaxRequest.readyState == 4){

						// Refresh the page is login is successful
						if(ajaxRequest.responseText.length == "380"){
							window.location = "'.$addr.this_page().'";
						}
					}
				}
				
				var queryString = "?message_id=" + message_id + "&mode=update";
				ajaxRequest.open("GET", "'.$addr.'/handle/update_message_ajax.php" + queryString, true);
				ajaxRequest.send(null); 
			}
			</script>
			<script language="javascript" type="text/javascript">
			function delete_message( message_id ){
				var ajaxRequest;  // The variable that makes Ajax possible!
				
				try{
					// Opera 8.0+, Firefox, Safari
					ajaxRequest = new XMLHttpRequest();
				} catch (e){
					// Internet Explorer Browsers
					try{
						ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
					} catch (e) {
						try{
							ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
						} catch (e){
							// Something went wrong
							alert("Your browser broke!");
							return false;
						}
					}
				}
				// Create a function that will receive data sent from the server
				ajaxRequest.onreadystatechange = function(){
					if(ajaxRequest.readyState == 4){

						// Refresh the page is login is successful
						if(ajaxRequest.responseText.length == "380"){
							window.location = "'.$addr.this_page().'";
						}
					}
				}
				
				var queryString = "?message_id=" + message_id + "&mode=delete";
				ajaxRequest.open("GET", "'.$addr.'/handle/update_message_ajax.php" + queryString, true);
				ajaxRequest.send(null); 
			}
			</script>
		';
		
		$query = mysql_query("SELECT * FROM messages WHERE recipient='$m_user_id' ORDER BY id DESC");
		
		$num_of_messages = mysql_num_rows($query);
		
		// See if messages for user exist
		if($num_of_messages > 0){
			
			$content .= '
				<form name="checks" id="checks">
			';
			
			while($message_array = mysql_fetch_array($query)){
				$user_query = mysql_query("SELECT name FROM users WHERE user_id='{$message_array['sender']}'");
				$user_array = mysql_fetch_assoc($user_query);
				
				$u_name = $user_array['name'];
			
				// If message is read
				if($message_array['readbool']){
					$content .='
						<div class="message read">
					';
					$readbool = 'read';
					$img_title = 'Mark as Unread';
					
				// Else if message isn't read
				}else{
					$content .='
						<div class="message unread">
					';
					$readbool = 'unread';
					$img_title = 'Mark as Read';
				}
				
				$content .= '
					<div class="check">
						<img title="'.$img_title.'"src="'.$addr.'/imgs/'.$readbool.'.png" onclick="update_message('.$message_array['message_id'].')" />
						<input type="checkbox" name="check" value="'.$message_array['id'].'" />
					</div>
					<div class="userdate">
						<P><a href="'.$addr.'/profile.php?id='.$message_array['sender'].'">'.$u_name.'</a></P>
						<P>'.$message_array['date'].'</P>
					</div>
					<div class="titlesnip">
						<P><a href="'.$addr.'/messages.php?read='.$message_array['message_id'].'">'.nl2br(stripslashes($message_array['title'])).'</a></P>
				';
					if(strlen($message_array['content']) > 30){
						$content .= '
							<P><a href="'.$addr.'/messages.php?read='.$message_array['message_id'].'">'.substr(stripslashes($message_array['content']),0,30).'...</a></P>
						';
					}else{
						$content .= '
							<P><a href="'.$addr.'/messages.php?read='.$message_array['message_id'].'">'.stripslashes($message_array['content']).'</a></P>
						';
					}
				$content .= '
					</div>
					<div class="delete">
						<img title="Delete" src="'.$addr.'/imgs/delete.png" onclick="delete_message('.$message_array['message_id'].')" />
					</div>
				</div>
				';
			}
			
			$content .= '
				</form>
			';
		}
		
	// Set to sent mode
	// retrieve and display sent messages
	}else if($mode == 'sent' && !isset($_GET['read'])){
	
		$content .= '
			<script language="javascript" type="text/javascript">
			function delete_message( message_id ){
				var ajaxRequest;  // The variable that makes Ajax possible!
				
				try{
					// Opera 8.0+, Firefox, Safari
					ajaxRequest = new XMLHttpRequest();
				} catch (e){
					// Internet Explorer Browsers
					try{
						ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
					} catch (e) {
						try{
							ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
						} catch (e){
							// Something went wrong
							alert("Your browser broke!");
							return false;
						}
					}
				}
				// Create a function that will receive data sent from the server
				ajaxRequest.onreadystatechange = function(){
					if(ajaxRequest.readyState == 4){

						// Refresh the page is login is successful
						if(ajaxRequest.responseText == ""){
							window.location = "'.$addr.this_page().'?mode=sent";
						}
					}
				}
				
				var queryString = "?message_id=" + message_id + "&mode=delete";
				ajaxRequest.open("GET", "'.$addr.'/handle/update_message_ajax.php" + queryString, true);
				ajaxRequest.send(null); 
			}
			</script>
		';
		$query = mysql_query("SELECT * FROM messages WHERE sender='$m_user_id' ORDER BY id DESC");
		
		$num_of_messages = mysql_num_rows($query);
		
		// See if messages for user exist
		if($num_of_messages > 0){
		
			$content .= '
				<form name="checks" id="checks">
			';
		
			while($message_array = mysql_fetch_array($query)){
				$user_query = mysql_query("SELECT name FROM users WHERE user_id='{$message_array['recipient']}'");
				$user_array = mysql_fetch_assoc($user_query);
				
				$u_name = $user_array['name'];
				
				$content .='
					<div class="message read">
						<div class="check">
							<input type="checkbox" name="check" value="'.$message_array['id'].'" />
						</div>
						<div class="userdate">
							<P><a href="'.$addr.'/profile.php?id='.$message_array['recipient'].'">To: '.$u_name.'</a></P>
							<P>'.$message_array['date'].'</P>
						</div>
						<div class="titlesnip">
							<P><a href="'.$addr.'/messages.php?mode=sent&read='.$message_array['message_id'].'">'.stripslashes($message_array['title']).'</a></P>
					';
						if(strlen($message_array['content']) > 30){
							$content .= '
								<P><a href="'.$addr.'/messages.php?mode=sent&read='.$message_array['message_id'].'">'.substr(stripslashes($message_array['content']),0,30).'...</a></P>
							';
						}else{
							$content .= '
								<P><a href="'.$addr.'/messages.php?mode=sent&read='.$message_array['message_id'].'">'.stripslashes($message_array['content']).'</a></P>
							';
						}
					$content .= '
						</div>
						<div class="delete">
							<img title="Delete" src="'.$addr.'/imgs/delete.png" onclick="delete_message('.$message_array['message_id'].')" />
						</div>
					</div>
				';
			}
			
			$content .= '
				</form>
			';
		}

	// Set to read mode
	}else if(isset($_GET['read'])){
		$message_id = $_GET['read'];
		
		// Retrieve message row from database
		$query = mysql_query("SELECT * FROM messages WHERE message_id='$message_id'");
		$message_exists = mysql_num_rows($query);
		
		// If the message doesn't exist refresh the page
		if(!$message_exists){
			refresh(this_page());
		}
		
		$message_array = mysql_fetch_assoc($query);
		
		// Get sender's name
		$sender_query = mysql_query("SELECT name FROM users WHERE user_id='{$message_array['sender']}'");
		$sender_array = mysql_fetch_assoc($sender_query);
		
		if($mode == 'sent'){
			$fromto = 'To';
		}else{
			$fromto = 'From';
		}
		
		$content .= '
			<div class="message_box">
				<div class="titleinfo">
					<P>'.$fromto.': '.$sender_array['name'].'</P>
					<P>"'.nl2br(stripslashes($message_array['title'])).'"</P>
					<P>'.$message_array['date'].'</P>
				</div>
				<div class="content">
					<hr />
					<P>'.nl2br(stripslashes($message_array['content'])).'</P>
				</div>
			</div>
		';
		
		// Mark message as read
		$update_query = mysql_query("UPDATE messages SET readbool='1' WHERE message_id='{$_GET['read']}' LIMIT 1") or die(mysql_error());
		
	// Set to compose mode
	}else if($mode == 'compose'){
		
		$content .= '
		
			<div class="compose_box">
				<div class="top" id="compose_box">
		';
				$recipient = $_GET['to'];
				$subject = $_GET['subject'];
				// Handles the form
				include $rel_addr.'/handle/compose_handle.php';
				
		$content .= '
				</div>
				<form action="'.this_page().'?mode=compose" method="POST">
				<div class="container"><label for="recipient">To: </label><input type="text" size="20" id="recipient" name="recipient" value="'.$recipient.'" /></div>
				<div class="container"><label for="title">Subject: </label><input type="text" size="20" id="subject" name="subject" value="'.stripslashes(stripslashes($subject)).'" /></div>
				<div class="container"><label for="message_content">Message: </label><textarea id="message_content" name="message_content">'.stripslashes(nl2br(stripslashes($message_content))).'</textarea>
				</div>
				<div class="container"><input type="submit" name="send" class="submit" value="Send" /></div>
				</form>
			</div>
		';
	}
	
	$content .= '
		</div>
	';
// else if not logged in
}else{
	$content .= '
		<P>You are not logged in. Redirecting to login page...</P>
	';
	refresh('/login.php','none',3);
}
/*
**   P U T    V A R S
**    O N    P A G E
*/
	top($title,$style);
	middle($header,$subtitle,$content,$side);
	bottom($navigation,$footer,$dbc);
?>
